from flask import Blueprint, jsonify, request, json
import pymysql as sql

user = Blueprint('user', __name__)

connect = sql.Connect(
    host='bj-cdb-hjbj4oh0.sql.tencentcdb.com',
    port=60670,
    user='root',
    passwd='Yuan2000_',
    db='tencentmysql',
    charset='utf8'
)
cursor = connect.cursor()

adminNum = '62'


@user.route('/', methods=['GET'])
def index():
    print("here is base")
    return jsonify('My Flask Wed')


@user.route('/login', methods=['POST'])
def login():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    UserName = json_data.get('UserName')
    Password = json_data.get('Password')
    sql = "SELECT ID FROM sys_user where UserName = '" + UserName + "' AND Password = '" + Password + "'"
    print(sql)
    cursor.execute(sql)
    temp = cursor.fetchall()
    print(temp)
    if temp == ():
        print("登录失败")
        return jsonify(0)
    else:
        print("登录成功")
        return jsonify(1)


@user.route('/updatepass', methods=['POST', 'GET'])
def updatepass():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    old_pass = json_data.get('old_pass')
    new_pass = json_data.get('new_pass')
    conf_pass = json_data.get('conf_pass')
    if new_pass != conf_pass:
        return jsonify(2)
    sql1 = "SELECT Password from sys_user where ID='" + adminNum + "'"
    print(sql1)
    cursor.execute(sql1)
    temp = cursor.fetchall()
    print(temp)
    if temp[0][0] == old_pass:
        sql2 = "UPDATE sys_user set Password = " + str(new_pass) + " WHERE ID = '" + adminNum + "'"
        print(sql2)
        cursor.execute(sql2)
        connect.commit()
        return jsonify(0)
    else:
        return jsonify(1)

